<?php
namespace app\member\service;
/**
 * 会员处理
 */
class MemberService extends \app\base\service\BaseService {

    /**
     * 登录用户
     * @param $username
     * @param $password
     * @param string $type
     * @return bool
     */
    public function loginUser($username = '', $password = '', $type = '') {
        if (empty($username) || empty($password)) {
            return $this->error('请输入帐号和密码!');
        }
        $config = target('member/MemberConfig')->getConfig();
        if (empty($type)) {
            $type = $config['reg_type'];
        }
        $type = strtolower($type);
        if ($type <> 'tel' && $type <> 'email') {
            return $this->error('登录类型错误!');
        }
        if ($type == 'tel') {
            if (!preg_match('/(^1[3|4|5|7|8][0-9]{9}$)/', $username)) {
                return $this->error('手机号码错误!');
            }
        }
        if ($type == 'email') {
            if (!filter_var($username, \FILTER_VALIDATE_EMAIL)) {
                return $this->error('邮箱账号不正确!');
            }
        }
        if (!preg_match('/^[a-zA-Z\d_]{6,18}$/', $password)) {
            return $this->error('密码必须为6-12个字符！');
        }
        $info = target('member/MemberUser')->getWhereInfo([
            $type => $username
        ]);
        if (empty($info)) {
            return $this->error('帐号或者密码输入错误!');
        }
        $password = md5($password);
        if ($info['password'] <> $password) {
            return $this->error('帐号或者密码输入错误!');
        }
        $config = \Config::get('dux.use');
        $loginData = array();
        $loginData['uid'] = $info['user_id'];
        $loginData['token'] = sha1($info[$type] . $password . $config['safe_key']);
        $userInfo = $this->getUser($info['user_id']);
        if (!$userInfo) {
            return false;
        }
        $loginData['info'] = $userInfo;
        return $this->success($loginData);
    }

    /**
     * 验证用户登录
     * @param $uid
     * @param $token
     * @param string $type
     * @return bool
     */
    public function checkUser($uid = '', $token = '', $type = '') {
        if (empty($uid) || empty($token)) {
            return $this->error('帐号登录失效!');
        }
        $config = target('member/MemberConfig')->getConfig();
        if (empty($type)) {
            $type = $config['reg_type'];
        }
        $type = strtolower($type);
        if ($type <> 'tel' && $type <> 'email') {
            return $this->error('帐号类型错误!');
        }
        $info = target('member/MemberUser')->getWhereInfo([
            'user_id' => $uid
        ]);
        if (empty($info)) {
            return $this->error('用户不存在!');
        }
        $config = \Config::get('dux.use');
        $verify = sha1($info[$type] . $info['password'] . $config['safe_key']);
        if ($token <> $verify) {
            return $this->error('登录验证失败,请重新登录!');
        }
        return $this->success();
    }

    /**
     * 重置密码
     * @param $username
     * @param $password
     * @param $code
     * @param string $type
     * @return bool
     */
    public function forgotUser($username = '', $password = '', $code = '', $type = '') {
        if (empty($username) || empty($password)) {
            return $this->error('请输入新密码!');
        }
        $config = target('member/MemberConfig')->getConfig();
        if (empty($type)) {
            $type = $config['reg_type'];
        }
        $type = strtolower($type);
        if ($type <> 'tel' && $type <> 'email') {
            return $this->error('帐号类型错误!');
        }
        if ($type == 'tel') {
            if (!preg_match('/(^1[3|4|5|6|7|8][0-9]{9}$)/', $username)) {
                return $this->error('手机号码错误!');
            }
        }
        if ($type == 'email') {
            if (!filter_var($username, \FILTER_VALIDATE_EMAIL)) {
                return $this->error('邮箱账号不正确!');
            }
        }
        if (!preg_match('/^[a-zA-Z\d_]{6,18}$/', $password)) {
            return $this->error('密码必须为6-12个字符！');
        }
        $info = target('member/MemberUser')->getWhereInfo([
            $type => $username
        ]);
        if (empty($info)) {
            return $this->error('该用户不存在!');
        }
        if ($config['verify_status']) {
            $status = $this->checkVerify($username, $code);
            if (!$status) {
                return $status;
            }
        }
        $data = array();
        $data['user_id'] = $info['user_id'];
        $data['password'] = md5($password);
        if (!target('member/MemberUser')->edit($data)) {
            return $this->error('重置密码失败,请稍候再试!');
        }
        return $this->success();
    }

    /**
     * 用户注册
     * @param $username
     * @param $password
     * @param $code
     * @param string $type
     * @return bool|void
     */
    public function regUser($username = '', $password = '', $code = '', $type = '') {
        if (empty($username) || empty($password)) {
            return $this->error('请输入帐号和密码!');
        }
        $config = target('member/MemberConfig')->getConfig();
        if (empty($type)) {
            $type = $config['reg_type'];
        }
        $type = strtolower($type);
        if ($type <> 'tel' && $type <> 'email') {
            return $this->error('帐号类型错误!');
        }
        if ($type == 'tel') {
            if (!preg_match('/(^1[3|4|5|7|8][0-9]{9}$)/', $username)) {
                return $this->error('手机号码错误!');
            }
        }
        if ($type == 'email') {
            if (!filter_var($username, \FILTER_VALIDATE_EMAIL)) {
                return $this->error('邮箱账号不正确!');
            }
        }
        if (!preg_match('/^[a-zA-Z\d_]{6,18}$/', $password)) {
            return $this->error('密码必须为6-12个字符！');
        }

        if ($config['reg_status'] == 0) {
            return $this->error('系统暂时停止开放注册!');
        }
        if (in_array($username, explode('|', $config['reg_ban_name']))) {
            return $this->error('当前账户名被禁止注册!');
        }
        if (in_array(\dux\lib\Client::getUserIp(), explode('|', $config['reg_ban_ip']))) {
            return $this->error('当前IP被禁止注册!');
        }
        if ($config['verify_status']) {
            $status = $this->checkVerify($username, $code);
            if (!$status) {
                return $status;
            }
        }
        $role = intval($config['reg_role']);
        if (empty($role)) {
            return $this->error('未设置正确角色!');
        }
        $info = target('member/MemberUser')->getWhereInfo([
            $type => $username
        ]);
        if (!empty($info)) {
            return $this->error('该用户已被注册!');
        }
        $data = array();
        $data[$type] = $username;
        $data['password'] = $password;
        $data['role_id'] = intval($config['reg_role']);
        if (!target('member/MemberUser')->saveData('add', $data)) {
            return $this->error(target('member/MemberUser')->getError());
        }
        return $this->success();
    }

    /**
     * 更新资料
     * @param $uid
     * @param array $data
     * @return bool
     */
    public function updateUser($uid, $data = []) {
        if (empty($data)) {
            return $this->error('账号资料获取失败!');
        }
        $data = [
            'user_id' => $uid,
            'nickname' => html_clear($data['nickname']),
            'avatar' => html_clear($data['avatar']),
            'province' => html_clear($data['province']),
            'city' => html_clear($data['city']),
            'region' => html_clear($data['region'])
        ];
        if (empty($data['user_id'])) {
            return $this->error('用户获取错误!');
        }
        if (empty($data['nickname'])) {
            return $this->error('请填写昵称!');
        }
        if (empty($data['province'])) {
            return $this->error('请选择省份!');
        }
        if (empty($data['city'])) {
            return $this->error('请选择城市!');
        }
        if (empty($data['region'])) {
            return $this->error('请选择区域!');
        }
        $config = target('member/MemberConfig')->getConfig();
        if (in_array($data['nickname'], explode('|', $config['reg_ban_name']))) {
            return $this->error('当前昵称被禁止使用!');
        }
        $count = target('member/MemberUser')->where(['nickname' => $data['nickname'], '_sql' => 'user_id <> ' . $data['user_id']])->count();
        if ($count) {
            return $this->error('该昵称已被使用!');
        }
        if (!target('member/MemberUser')->edit($data)) {
            return $this->error(target('member/MemberUser')->getError());
        }
        return $this->success();

    }

    /**
     * 获取账户信息
     */
    public function getUser($uid) {
        $info = target('member/MemberUser')->getInfo($uid);
        if (empty($info)) {
            return $this->error('用户不存在!');
        }
        $infoData = [
            'user_id' => $info['user_id'],
            'tel' => $info['tel'],
            'email' => $info['email'],
            'nickname' => $info['nickname'],
            'avatar' => $info['avatar'],
            'province' => $info['province'],
            'city' => $info['city'],
            'region' => $info['region'],
            'reg_time' => $info['reg_time'],
        ];
        $accountInfo = target('member/PayAccount')->getWhereInfo(['A.user_id' => $uid]);
        if (empty($accountInfo)) {
            return $this->error('账户不存在!');
        }
        $infoData['money'] = $accountInfo['money'];
        $infoData['spend'] = $accountInfo['spend'];
        $infoData['charge'] = $accountInfo['charge'];
        return $this->success($infoData);
    }

    /**
     * 获取验证码
     * @param string $receive
     * @param string $content
     * @param int $type
     * @return bool
     */
    public function getVerify($receive = '', $content = '', $code = 0, $type = 0) {

        $config = target('member/MemberConfig')->getConfig();
        $typelist = target('tools/ToolsSendConfig')->typeList();
        $typeInfo = $typelist[$config['verify_type']];
        if (!target($typeInfo['target'], 'send')->check(['receive' => $receive])) {
            return $this->error(target($typeInfo['target'], 'send')->getError());
        }
        $info = target('member/MemberVerify')->where([
            'receive' => $receive,
            'type' => $type
        ])->order('verify_id desc')->find();
        if (!empty($info)) {
            if ($info['time'] + intval($config['verify_second']) > time()) {
                return $this->error($config['verify_second'] . '秒内无法再次获取验证码!');
            }
            $where = array();
            $where['receive'] = $receive;
            $where['type'] = $type;
            $where['_sql'] = 'time > ' . time() - $info['verify_minute'] * 60;
            $count = target('member/MemberVerify')->where($where)->count();
            if ($count >= $config['verify_minute_num']) {
                return $this->error('验证码获取太频繁,请过段时间再试!');
            }
        }
        if (!$code) {
            $code = $this->getCode(6);
        }
        $data = array();
        $data['time'] = time();
        $data['code'] = $code;
        $data['receive'] = $receive;
        $data['expire'] = $config['verify_expire'];
        $data['type'] = $type;
        $data['status'] = 0;
        if (!target('member/MemberVerify')->add($data)) {
            return $this->error('验证码获取失败,请稍候再试!');
        }
        if (empty($content)) {
            $content = $config['verify_tpl'];
        }
        $content = str_replace('{code}', $code, $content);
        $content = str_replace('{name}', $config['verify_name'], $content);
        $content = str_replace('{expire}', $config['verify_expire'] / 60, $content);
        $status = target('tools/Tools', 'service')->addQuene([
            'receive' => $receive,
            'type' => $config['verify_type'],
            'title' => '验证码发送',
            'content' => $content,
        ]);
        if (!$status) {
            return $this->error(target('tools/Send', 'service')->getError());
        }
        return $this->success();
    }

    /**
     * 验证验证码
     * @param $receive
     * @param $code
     * @param int $type
     * @return bool
     */
    public function checkVerify($receive, $code, $type = 0) {
        $info = target('member/MemberVerify')->where([
            'receive' => $receive,
            'code' => $code,
            'type' => $type
        ])->order('verify_id desc')->find();
        if (empty($info)) {
            return $this->error('验证码不正确!');
        }
        if ($info['status']) {
            return $this->error('验证码已使用!');
        }
        if ($info['time'] + $info['expire'] < time()) {
            return $this->error('验证码已过期!');
        }
        $data = array();
        $data['verify_id'] = $info['verify_id'];
        $data['status'] = 1;
        target('member/MemberVerify')->edit($data);
        return $this->success();
    }

    /**
     * 生成验证码
     * @param int $length
     * @return int
     */
    public function getCode($length = 6) {
        return rand(pow(10, ($length - 1)), pow(10, $length) - 1);
    }

    /**
     * 添加发信队列
     * @param $receive
     * @param $content
     * @param array $param
     * @param string $type
     * @return bool
     */
    public function sendMessage($receive, $title, $content, $param = [], $type = '') {
        $config = target('member/MemberConfig')->getConfig();
        $typelist = target('tools/ToolsSendConfig')->typeList();
        if (!$type) {
            $type = $config['verify_type'];
        }
        if (!$type) {
            return $this->error('发信类型未设置!');
        }
        $typeInfo = $typelist[$type];
        if (!target($typeInfo['target'], 'send')->check(['receive' => $receive])) {
            return $this->error(target($typeInfo['target'], 'send')->getError());
        }
        $content = str_replace('{name}', $config['verify_name'], $content);
        $status = target('tools/Tools', 'service')->addQuene([
            'receive' => $receive,
            'type' => $type,
            'title' => $title,
            'content' => $content,
            'param' => $param
        ]);
        if (!$status) {
            return $this->error(target('tools/Send', 'service')->getError());
        }
        return $this->success();

    }

    /**
     * 上传文件
     * @param $userId
     * @param int $width
     * @param int $height
     * @return bool
     */
    public function upload($userId, $type = '', $width = 0, $height = 0, $httpUrl = true) {
        $config = array();
        $config['dir_name'] = date('Y-m-d');
        if ($type) {
            $config['upload_exts'] = $type;
        }
        if ($width && $height) {
            $config['thumb_width'] = $width;
            $config['thumb_height'] = $height;
            $config['thumb_status'] = true;
            $config['thumb_type'] = 2;
        }
        $fileInfo = target('base/Upload')->upload($config);
        if (!$fileInfo) {
            return $this->error(target('base/Upload')->getError());
        }
        $list = [];
        if($fileInfo['url']) {
            $list[] = $fileInfo;
        }else {
            $list = $fileInfo;
        }

        if($httpUrl) {
            $http = 'http://' . trim($_SERVER["HTTP_HOST"], '/') . ROOT_URL;
        }else {
            $http = '';
        }
        $returnData = [];
        foreach($list as $key => $data) {
            $data['user_id'] = $userId;
            $data['time'] = time();
            $data['url'] = $http . $data['url'];
            $data['original'] = $http . $data['original'];
            if (!target('member/MemberFile')->add($data)) {
                return $this->error('上传失败,请稍候再试!');
            }
            $returnData[$key] = $data;
        }
        if(count($list) <= 1) {
            $returnData = current($returnData);
        }
        return $this->success($returnData);
    }


}
